//存储以id-datas—tittlesId形式的数据到endocrineInfo_idDatas中，528条datas
var MongoClient = require("mongodb").MongoClient;
var DB_URL = "mongodb://localhost:27017/endocrineInfo";
var fs = require('fs');

var DataList = [];
var Datas;

//转成对象
function strMapToObj(strMap) {
  let obj = Object.create(null);
  for (let [k,
    v]of strMap) {
    obj[k] = v;
  }
  return obj;
}
//转成json
function strMapToJson(strMap) {
  return JSON.stringify(strMapToObj(strMap));
}
//插入数据到mongodb
function insertData(db) {
  var devices = db.collection('idDatas');
  devices.insert(DataList, function(error, result) {
    if (error) {} else {
  console.log(result.result.n);
    }
    db.close();
  });
}
//读取文件
fs.readdir("/Users/eh/Documents/mywork/htm1/three", function(err, files) {
  if (err) {
    console.log(err);
    return;
  }
  console.log(files.length);
  files.forEach(function(filename) {

    var myMap = new Map();
    var readline = require('linebyline'),
      rl = readline('/Users/eh/Documents/mywork/htm1/three/' + filename);
    var temp1;
    var arrayValue = [];
    rl.on('line', function(line, lineCount, byteCount) {
      var regex = /^【(.*)】/; //有【】
      var regex1 = /^[^【]|^$/;
      var regex2 = /^[^【】$]/; //没有中括号
      var regex3 = /^$/; //空白行
      if (line.match(regex)) { //匹配【】
        // console.log(line);
        temp1 = line.match(regex).input.toString();
        myMap.set(temp1, '');
      } else if (line.match(regex1)) {

        if (line.match(regex3)) { //空白行
          var valueBlank1 = myMap.get(temp1);
          var valueBlank = line.match(regex3).input;
          myMap.set(temp1, valueBlank1);
        }
        if (line.match(regex2)) { //有值
          var value1 = myMap.get(temp1);
          var value = line.match(regex2).input;
          if (temp1 != '【特征表现】') {
            myMap.set(temp1, value1 + value);
          } else {
            var a=value.toString();
            var b=a.replace(/^\d{1,2}./,'');
            var c=b.trim();
            arrayValue.push(c);
            myMap.set(temp1, arrayValue);
          }
        }

      }
    }).on('close', function() {

      var list=[];
      for (let [k,v] of myMap) {
        // console.log(v);
        list.push(v);
      }
      var newMap=new Map();
      newMap.set('datas',list);
      var arrayTitle=new Array();
      arrayTitle=["综合征中文名","英文全名","中文别名","英文别名","中文别名2","英文别名2","中文别名3","英文别名3","OMIM","英文缩写","英文缩写2","英文缩写3","好发年龄","遗传方式","病因","基因定位","临床表现","特征表现"]
      newMap.set('titlesId',arrayTitle);
        Datas = strMapToObj(newMap);
        DataList.push(Datas);
        MongoClient.connect(DB_URL, function(error, db) {
        insertData(db);
      });

    });

  });
});
